package com.example.notepadapp.db;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import androidx.annotation.Nullable;

import com.example.notepadapp.been.Notepad;

import java.util.ArrayList;
import java.util.List;

// 数据库帮助类
public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "notepad.db";
    private static final int DATABASE_VERSION = 1;

    /**
     * 构造方法
     * @param context 上下文.
     */
    public DatabaseHelper(@Nullable Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    /**
     * 数据库只在第一次创建的时候调用该方法
     * @param db The database.
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d("DB_TAG", "创建数据库: ");
        // 1.创建字段
        String sql = "create table notepad(id integer primary key autoincrement,content text,time text)";
        // 2.执行sql语句
        db.execSQL(sql);
    }

    /**
     * 升级数据库版本的时候调用
     * @param db The database.
     * @param oldVersion The old database version.
     * @param newVersion The new database version.
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.d("DB_TAG", "更新数据库: ");
    }

    // 新增数据
    public void insert(Notepad notepad) {
        String sql = "insert into notepad(content, time) values(?, ?)";
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL(sql, new Object[]{notepad.getContent(), notepad.getTime()});
    }

    // 查询所有数据
    @SuppressLint("Range")
    public List<Notepad> findAll() {
        String sql = "select * from notepad";
        SQLiteDatabase db = getWritableDatabase();
        Cursor cursor = db.rawQuery(sql, null);
        List<Notepad> list = new ArrayList<>();
        while(cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String content = cursor.getString(cursor.getColumnIndex("content"));
            String time = cursor.getString(cursor.getColumnIndex("time"));
            Notepad notepad = new Notepad();
            notepad.setId(id);
            notepad.setContent(content);
            notepad.setTime(time);
            list.add(notepad);
        }
        cursor.close();
        return list;
    }

    // 删除数据
    public void delete(Notepad notepad) {
        String sql = "delete from notepad where id=?";
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL(sql, new Object[]{notepad.getId()});
    }

    // 修改数据
    public void update(Notepad notepad) {
        String sql = "update notepad set content=?, time=? where id=?";
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL(sql, new Object[]{notepad.getContent(), notepad.getTime(), notepad.getId()});
    }
}
